<template>
  <div class="invoices_container">
    <van-nav-bar title="发票核销" />


    <van-checkbox-group v-model="checkedBill" ref="checkboxGroup">
      <van-row v-for="(item, index) in invoices" :key="index" type="flex" align="center">
        <van-col span="2" style="text-align: center;">
          <van-checkbox :name="item.invoice_code" style="margin-left:10px"> </van-checkbox>
        </van-col>
        <van-col span="22">
          <div class="invoice-box">
            <van-row gutter="20">
              <van-col :span="23">
                <template>
                  <van-row>
                    <van-col :span="12">
                      <span class="invioce-lable">发票号</span>
                      <span class="invioce-value">{{ item.invoice_code }}</span>
                    </van-col>
                    <van-col :span="12" style="text-align: right;">
                      <!-- <span class="invioce-lable">发票号</span> -->
                      <span class="invioce-value">{{ item.idowner_name }}</span>
                    </van-col>

                  </van-row>
                  <van-divider dashed />
                  <van-row>
                    <van-col :span="24">
                      <span class="invioce-lable">销方名称</span>
                      <span class="invioce-value">{{ item.seller_name }}</span>
                    </van-col>
                  </van-row>
                  <van-row style="margin-top:10px">
                    <van-col :span="24">
                      <span class="invioce-lable">购方名称</span>
                      <span class="invioce-value">{{ item.buyer_name }}</span>
                    </van-col>
                  </van-row>

                  <van-divider dashed />
                  <van-row style="margin-top:10px">
                    <van-col :span="10">
                      <span class="invioce-lable">发票金额</span>
                      <span class="invioce-value"><b style="color:red"> ¥ {{ item.invoice_amount }}</b></span>
                    </van-col>
                    <van-col :span="14" style="text-align: right;">
                      <span class="invioce-lable">本次核销金额 <b style="color:red">¥</b></span>
                      <span class="invioce-value">
                        <input v-model="item.writeOffAmount" @input="hanldeInput(item)" type="number"
                          placeholder="请输入" class="invioce-input" :disabled="!item.isChecked"
                          style="font-size:14px; width: 80px;border:none;border-bottom: 1px solid #ddd;">
                      </span>
                    </van-col>
                  </van-row>
                </template>
              </van-col>

              <van-col :span="1">
                <div class="hole-box">
                  <div class="hole-item"></div>
                  <div class="hole-item"></div>
                  <div class="hole-item"></div>
                  <div class="hole-item"></div>
                  <div class="hole-item"></div>
                  <div class="hole-item"></div>
                  
                </div>

              </van-col>

            </van-row>





          </div>

        </van-col>
      </van-row>
    </van-checkbox-group>



    <van-submit-bar button-text="结算" @submit="handleSubmit">
      <template #tip v-if="isShowTip">
        本次核销金额不能大于未票核金额
      </template>
      <template #default>
        <van-row gutter="20" type="flex" align="center" style="width: 100vw;">
          <van-col>
            <van-checkbox v-model="checkAll">全选</van-checkbox>
          </van-col>
          <van-col>
            <div>未票核金额:<b style="color:red">{{ unamount }} </b> </div>
            <div>本次核销金额:<b style="color:red">{{ writeOffTotal }}</b></div>
          </van-col>


        </van-row>


      </template>




    </van-submit-bar>



  </div>
</template>
<script>
import Vue from 'vue'
import qs from 'qs'
import { Checkbox, CheckboxGroup, Toast, Col, Row, NavBar, SubmitBar, Divider } from 'vant';
import { number } from 'echarts';
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Toast)
Vue.use(Col);
Vue.use(Row);
Vue.use(NavBar);
Vue.use(SubmitBar);
Vue.use(Divider);

export default {
  name: 'invoicecancel',
  data() {
    return {
      checkAll: false,
      checkedBill: [],
      data: null,
      bo: null,
      id: null,
      unamount: null,
      amount_total: null,
      titles: null,
      invoices: [],
      selectedPeople: [],

      realObj: "",
      realId: "",

      currentIndex: 0,
    };
  },
  watch: {
    checkedBill: {
      handler(val) {

        // 控制输入
        this.invoices = this.invoices.map(item => {
          item.isChecked = val.indexOf(item.invoice_code) !== -1
          if (!item.isChecked) {
            item.writeOffAmount = ""
          }
          return item
        })

        this.autoCalculation()






      }
    },
    checkAll: {
      handler(val) {
        if (val) {
          this.$refs.checkboxGroup.toggleAll(true);
        } else {
          this.$refs.checkboxGroup.toggleAll();
        }
      }
    }
  },
  mounted() {
    this.getData()
  },
  computed: {
    writeOffTotal() {
      const res = this.invoices.reduce((pre, item) => {
        return pre + Number(item.writeOffAmount)
      }, 0)
      return res.toFixed(2)
    },
    isShowTip() {
      return Number(this.unamount) < Number(this.writeOffTotal)
    }
  },
  methods: {

    autoCalculation() {
      const checkedArr = this.invoices.filter(item => item.isChecked).sort((a, b) => {
        return a.invoice_amount - b.invoice_amount
      })

      let checkedTotal = 0;
      let unamount = Number(this.unamount)
      // let unamount = 205.13


      for (let i = 0; i < checkedArr.length; i++) {
        const checkItem = checkedArr[i]
        const invoice_amount = Number(checkItem.invoice_amount)
        if (checkedTotal !== invoice_amount) {
          checkedTotal += invoice_amount
        }

        if (checkedTotal < unamount) {
          checkItem.writeOffAmount = checkItem.invoice_amount
        } else {
          checkItem.writeOffAmount = (invoice_amount - (checkedTotal - unamount)).toFixed(2)
          checkedTotal = unamount
        }
      }

    },

    getData() {
      let realObj = this.$route.query.realObj || '';
      let realId = this.$route.query.realId || '';

      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });


      let data = { [realObj + '_id']: realId }
      this.axios({
        method: 'post',
        url: '/api/' + realObj + '.fphx.do',
        data: qs.stringify(data)
      }).then(res => {

        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {

          if (res.data.flag === 0) {
            const jsondata = res.data.jsondata

            this.bo = jsondata.bo;
            this.id = jsondata.id;
            this.unamount = jsondata.unamount;
            this.amount_total = jsondata.amount_total;
            this.titles = jsondata.titles;
            this.invoices = (jsondata.invoices || []).map(item => {
              return { writeOffAmount: "", isChecked: false, ...item }
            });

          }
        }
      }).finally(() => {
        Toast.clear()
      })
    },
    onSubmit() { },
    // handleCheckAllorNot(){
    //   checkedBill

    //   this.checkedBill = this.invoices.map()

    // },
    hanldeInput(item) {
      console.log(item.writeOffAmount)

      if (item.writeOffAmount) {
        const invoice_amount = Number(item.invoice_amount)
        const writeOffAmount = Number(item.writeOffAmount)

        if (invoice_amount < writeOffAmount) {
          Toast("核销金额不能大于发票金额")
        }

      }


    },








    handleSubmit() {


      let data = {}
      data[this.idobject + '_id'] = this.id
      data['boxnoexbill_unamount'] = this.unamount
      data['boxnoexbill_feebid'] = this.id


      data['boxnoexbill_listcheck'] = this.invoices.reduce((pre, item) => {
        return item.isChecked ? `${pre}${item.id};` : `${pre}`
      }, '')


      data['writeamount'] = this.invoices.reduce((pre, item) => {
        return item.isChecked ? `${pre}${item.writeOffAmount};` : `${pre}`
      }, '');

      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });


      this.axios({
        method: 'post',
        url: '/api/' + this.bo + '.fphxsave.do',
        data: qs.stringify(data)
      }).then(res => {
        if (res.data.flag == '0') {
          Toast(res.data.jsondata.msg)
          setTimeout(() => {
            this.$router.go(-1)
          }, 1000)
        } else {
          Toast(res.data.jsondata.msg)
        }
      }).finally(() => {
        Toast.clear()
      })

    },


    cancel() {
      this.$router.go(-1);
    },

  }
};
</script>
<style>

.hole-box{
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.hole-item{
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #f0f0f0;
  margin:10px auto

}
.invoice-box {
  width: 95%;
  background-color: #fff;
  box-sizing: border-box;
  padding: 10px;
  border-radius: 6px;
  margin: 10px auto;
  overflow: hidden;

}

.invioce-lable {
  font-size: 12px;
  color: #f66f2c;
  margin-right: 10px;
}

.invioce-value {
  font-size: 14px;
  color: #303133
}




.invoices_container {

  width: 100%;
  min-height: 100vh;
  background-color: #f9f9f9
}
</style>
